import * as path from "path";
import * as workerpool from "workerpool";
import type { Pool } from "workerpool";
import * as vscode from "vscode";

export class TurboRenderer {
  private pool: Pool;
  private cache = new Map<string, string>();

  constructor(context: vscode.ExtensionContext) {
    this.pool = workerpool.pool(
      path.join(context.extensionPath, "dist", "render.worker.js"), // 修改为 dist 目录
      { maxWorkers: 4 }
    );
  }

  async render(code: string): Promise<string> {
    const cacheKey = this.createHash(code);
    if (this.cache.has(cacheKey)) {
      return this.cache.get(cacheKey)!;
    }

    try {
      const svg = await this.pool.exec("renderMermaid", [code]);
      this.cache.set(cacheKey, svg);
      return svg;
    } catch (err) {
      throw new Error(`渲染失败: ${(err as Error).message}`);
    }
  }

  dispose() {
    this.pool.terminate();
  }

  private createHash(str: string): string {
    let hash = 0;
    for (let i = 0; i < str.length; i++) {
      hash = (hash << 5) - hash + str.charCodeAt(i);
      hash |= 0;
    }
    return hash.toString(36);
  }
}
